import {useEffect, useRef, useState, KeyboardEvent, MouseEvent, useCallback} from "react";
import { Form } from 'antd';
import { EnumRouter } from "@/constants";
import {RespDataType, getUserInfo, login, getCaptchaImage } from "./api";
import BGParticle from "./BGParticle";
import BgImg from "./img/bg.png";

export const useLogin = () => {
    const [ loading, setLoading ] = useState(true);
    const [ submitting, setSubmitting ] = useState(false);
    const [ captchaImageInfo, setCaptchaImageInfo ] = useState<RespDataType.ICaptchaImageInfo>({
        img: "",
        uuid: ""
    });
    const [form] = Form.useForm();
    const canvasRef = useRef<HTMLCanvasElement>();

    useEffect(() => {
        if(!loading){
            const particle = new BGParticle(canvasRef.current);
            particle.init();
            return () => {
                particle.destroy();
            }
        }
    }, [loading]);

    useEffect(() => {
        const handleLoadImage = () =>  setLoading(false);
        loadImageAsync(BgImg).then(handleLoadImage).catch(handleLoadImage);
        fetchCaptchaImage();
    }, []);

    // 获取验证码图片
    const fetchCaptchaImage = useCallback(() => {
        getCaptchaImage().then((resp) => {
            resp.data.img = "data:image/png;base64,"+resp.data.img
            setCaptchaImageInfo(resp.data);
        })
    }, [])

    const handleSubmit = (e?:KeyboardEvent<HTMLInputElement> | MouseEvent<HTMLElement>) => {
        if(e.type == "click" || (e as KeyboardEvent<HTMLInputElement>).keyCode == 13){
            setSubmitting(true);
            form.validateFields().then((resp) => {
                const { loginName, password, code } = resp;
                login({username: loginName, password, code, uuid: captchaImageInfo.uuid}).then((resp) => {
                    getUserInfo().then(() => {
                        window.location.href = EnumRouter.appRoot;
                    });

                    setSubmitting(false);
                }).catch((e) => {
                    setSubmitting(false)
                });

            }).catch((e) => {

                setSubmitting(false)
            })
        }
    }

    return { loading, submitting, BgImg, canvasRef, handleSubmit, form, captchaImageInfo, fetchCaptchaImage }
}

const loadImageAsync = (url: string) => {
    return new Promise(function(resolve, reject) {
        const image = new Image();
        image.onload = () => {
            resolve(url);
        };
        image.onerror = () => {
            console.error('图片载入错误')
        };
        image.src = url;
    });
}
